

package Database;

import java.net.ConnectException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class save_puzzle {
    public void save_puzle(String admin, int type, ArrayList ques, String name)
    {
        Connection con=Connect.Connect.Con();
            try {
                // Save to puzzle table
                int adminid=this.getadminID(admin);
                PreparedStatement st=con.prepareStatement("insert into Puzzle values(?,?,?)");
                st.setString(1, name);
                st.setInt(2, adminid);
                st.setInt(3, type);
                st.executeUpdate();
                st.close();
                //Insert for each qustion
                for (int i = 0; i < ques.size(); i++) {
                    String[] cut=ques.get(i).toString().split("&&");
                    int qtype=0;
                    if(cut[3].equals("false"))
                    {
                        qtype=1;
                    }
                    String que=cut[0];
                    String ans=cut[1];
                    String posi=cut[2];
                    PreparedStatement sat=con.prepareStatement("insert into Pu_Question values(?,?,?,?,?)");
                    sat.setInt(1, get_puzz_id());
                    sat.setString(2, que);
                    sat.setString(3, ans);
                    sat.setInt(4, qtype);
                    sat.setString(5, posi);
                    sat.executeUpdate();
                    sat.close();
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Can not insert date into Puzzle table");
            }
    }
    public int getadminID(String name)
    {
        int kq = 0;
        try {
            ResultSet set=Connect.Connect.Con().createStatement().executeQuery("select * from Admin where account='" + name + "'");
            if(set.next())
            {
                kq=set.getInt(1);
            }
            set.close();
            Connect.Connect.Con().close();
        } catch (SQLException ex) {
            Logger.getLogger(save_puzzle.class.getName()).log(Level.SEVERE, null, ex);
        }
        return kq;
    }
    public static int get_puzz_id()
    {
        int kq=0;
        ResultSet set=null;
        try {
            set = Connect.Connect.Con().createStatement().executeQuery("select * from Puzzle order by PuzzleID desc");
            if(set.next())
            {
                kq=set.getInt(1);
            }
            set.close();
            Connect.Connect.Con().close();
        } catch (Exception ex) {
            Logger.getLogger(save_puzzle.class.getName()).log(Level.SEVERE, null, ex);
        }
        return kq;
    }
}
